<template>
  <div class="container">
    <!-- 操作控制区 -->
    <div class="control-panel">
      <el-button
        type="primary"
        :loading="scanLoading"
        @click="startScan"
      >
        开始扫描
      </el-button>

      <el-button
        type="success"
        :disabled="selectedDevices.length === 0"
        @click="handleUpgrade"
      >
        升级选中设备 ({{ selectedDevices.length }})
      </el-button>
    </div>

    <!-- 设备表格 -->
    <el-table
      :data="devices"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="scanLoading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="hostname" label="设备名称" width="180" />
      <el-table-column prop="ip" label="IP地址" width="130" />
      <el-table-column prop="mac" label="MAC地址" width="180" />
      <el-table-column prop="sn" label="序列号" width="200" />
      <el-table-column prop="version" label="固件版本">
        <template #default="{ row }">
          <el-tag :type="versionTagType(row.version)">
            {{ row.version }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="condition" label="状态">
        <template #default="{ row }">
          <el-progress
            v-if="row.condition?.includes('%')"
            :percentage="parseInt(row.condition.match(/\d+/))"
            :status="row.condition.includes('失败') ? 'exception' : 'success'"
            style="width: 80%"
          />
          <span v-else>{{ row.condition }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button link type="primary" @click="showDetail(row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 日志面板 -->
    <div class="log-panel">
      <div class="log-header">
        <span>操作日志</span>
        <div>
          <el-button size="small" @click="clearLogs">清空</el-button>
          <el-switch
            v-model="autoScroll"
            active-text="自动滚动"
            inactive-text="锁定"
          />
        </div>
      </div>
      <div class="log-content" ref="logContainer">
        <div
          v-for="(log, index) in logs"
          :key="index"
          class="log-item"
          :class="log.type"
        >
          <span class="timestamp">{{ log.timestamp }}</span>
          <span class="message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted,onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 设备数据
const devices = ref([])
const selectedDevices = ref([])
const scanLoading = ref(false)

// 日志系统
const logs = ref([])
const autoScroll = ref(true)
const logContainer = ref(null)

// 升级状态轮询
const upgradeStatusInterval = ref(null)
const pollingDevices = ref(new Set())

// 初始化加载
onMounted(() => {
  addLog('系统初始化完成', 'info')
})

// 组件卸载时清除定时器
onUnmounted(() => {
  stopStatusPolling()
})

// 扫描设备
const startScan = async () => {
  try {
    scanLoading.value = true
    addLog('开始网络设备扫描...', 'info')

    const { data } = await axios.get('http://127.0.0.1:20100/api/scan',null,{
      headers:{
        'Content-Type':'application/json'
      }
    })
    devices.value = (data.devices || []).map(device => ({
      ...device,
      condition: '待升级'
    }))
    if (data.devices == null) {
      addLog(`扫描完成，未查询到设备`, 'success')
    }
    addLog(`扫描完成，共发现 ${data.total} 台设备`, 'success')
    ElMessage.success(`发现 ${data.total} 台设备`)
  } catch (error) {
    addLog(`扫描失败: ${error.message}`, 'error')
    ElMessage.error('扫描操作失败')
  } finally {
    scanLoading.value = false
  }
}

// 处理设备选择
const handleSelectionChange = (selection) => {
  selectedDevices.value = selection
}

// 版本标签样式
const versionTagType = (version) => {
  return version.startsWith('2.2') ? 'success' : 'warning'
}

// 日志管理
const addLog = (message, type = 'info') => {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.unshift({ timestamp, message, type })

  // 自动滚动到底部
  if (autoScroll.value) {
    nextTick(() => {
      if (logContainer.value) {
        logContainer.value.scrollTop = logContainer.value.scrollHeight
      }
    })
  }
}

const clearLogs = () => {
  logs.value = []
}

// 设备升级处理
const handleUpgrade = async () => {
  try {
    const deviceList = selectedDevices.value.map(d => d.ip)
    addLog(`开始升级 ${deviceList.length} 台设备...`, 'info')
    devices.value = devices.value.map(device =>
      deviceList.includes(device.ip)
        ? { ...device, condition: '准备升级...' }
        : device
    )

    startStatusPolling(deviceList)

    const { data } = await axios.post('http://127.0.0.1:20100/api/upgrade', {
      devices: deviceList
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    // 处理响应
    addLog(`升级完成: 成功 ${data.success} 台, 失败 ${data.failed} 台`, 'info')
    ElMessage.success(`升级结果: 成功 ${data.success} 台, 失败 ${data.failed} 台`)

    // 显示详细结果
    data.details.forEach(d => {
      if(d.status === 'success') {
        addLog(`${d.ip} 升级成功`, 'success')
      } else {
        addLog(`${d.ip} 升级失败: ${d.error}`, 'error')
      }
    })

  } catch (error) {
    addLog(`升级失败: ${error.message}`, 'error')
    ElMessage.error('升级操作失败')
  }
}

// 启动状态轮询
const startStatusPolling = (deviceIPs) => {
  // 清空旧数据
  stopStatusPolling()
  pollingDevices.value = new Set(deviceIPs)

  // 立即执行第一次查询
  fetchUpgradeStatus()

  // 设置定时器（每1秒轮询一次）
  upgradeStatusInterval.value = setInterval(() => {
    fetchUpgradeStatus()
  }, 1000)
}

// 停止状态轮询
const stopStatusPolling = () => {
  if (upgradeStatusInterval.value) {
    clearInterval(upgradeStatusInterval.value)
    upgradeStatusInterval.value = null
  }
  pollingDevices.value.clear()
}

// 获取升级状态
const fetchUpgradeStatus = async () => {
  const currentDevices = [...pollingDevices.value]

  for (const ip of currentDevices) {
    try {
      const { data } = await axios.get(
        `http://${ip}/firmware-upgrade-status`,
        { timeout: 5000,
        withCredentials:false
        }
      )

      // 更新设备状态
      const device = devices.value.find(d => d.ip === ip)
      if (device) {
        device.condition = data.msg

        // 检测升级完成状态
        if (data.msg.includes('100%') || data.msg.includes('更新完成')) {
          pollingDevices.value.delete(ip)
          addLog(`${ip} 升级完成`, 'success')
        }
        if (data.msg == " "){

        }
        if (data.msg.includes('即将开始更新')) {
        }
      }
    } catch (error) {
      pollingDevices.value.delete(ip)
      addLog(`${ip} 状态获取失败: ${error.message}`, 'error')
    }
  }

  // 所有设备完成时停止轮询
  if (pollingDevices.value.size === 0) {
    stopStatusPolling()
    addLog('所有设备状态更新完成', 'success')
    ElMessage.success('设备升级完成')
  }
}

</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.control-panel {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.log-panel {
  margin-top: 30px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.log-header {
  padding: 12px 20px;
  background: #f5f7fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

.log-content {
  height: 200px;
  overflow-y: auto;
  padding: 10px 20px;
  background-color: #fafafa;
}

.log-item {
  padding: 8px 0;
  font-family: 'Menlo', monospace;
  display: flex;
  gap: 15px;
  font-size: 14px;
}

.log-item .timestamp {
  color: #909399;
  min-width: 80px;
}

.log-item.error .message {
  color: #f56c6c;
}

.log-item.success .message {
  color: #67c23a;
}

.log-item.info .message {
  color: #909399;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  font-family: monospace;
}
</style>
